package com.fms.aspect;

import com.fms.entity.SysUser;
import com.fms.security.CheckUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;


/*
定义一些通用操作的切面
 */
@Component
@Aspect
@Slf4j
@RequiredArgsConstructor
public class CommonAspect {
    private  final BCryptPasswordEncoder bCryptPasswordEncoder;
    private final CheckUtils checkUtils;
    @Pointcut("@annotation(com.fms.annotation.HandleSensitiveMessage)")
    private void passwordPt(){}
    /**
     * 密码加密aop,用于密码自动加密,加密前会校验密码格式
     */
    @Before("passwordPt()")
    public void passwordEncrypt(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        for (int i=0;i<args.length;i++){
            if(args[i] instanceof SysUser user){
                if(user.getPassword()!=null){
                    //密码格式校验
                    checkUtils.checkPasswordSyntax(user.getPassword());
                    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
                }
                if(user.getRealId()!=null){
                    user.setShowId(user.getRealId().substring(user.getRealId().length()-6));
                    user.setRealId(bCryptPasswordEncoder.encode(user.getRealId()));
                }
                args[i]=user;
            }
        }
    }
}
